<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { Chart } from "@antv/g2"; // 修正导入语句
import axios from "axios";
import { schemeTableau10 } from "d3-scale-chromatic";

// 响应式数据
const form = reactive({
  name: "",
  file: "",
  myFile: "",
});

// 图表实例
let timer = null;
let diskDataCache = null; // 缓存初始的磁盘数据

onMounted(() => {
  initG2Chart();
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
  if (chart) {
    chart.destroy();
  }
});

// 更新图表数据
const updateChartData = async () => {
  try {
    const percentageData = await axios.get("http://localhost:2000/data1.json");

    // 获取当前数据并更新
    const currentData = chart.options.data;
    const updatedData = updateNodeData(currentData, percentageData.data);

    // 更新图表数据
    chart.changeData(updatedData);
  } catch (error) {
    console.error("数据更新失败:", error);
  }
};

// 初始化 G2Plot 图表
const initG2Chart = async () => {
  try {
    const chart = new Chart({
      container: "container",
      autoFit: true,
      draggable: true, // 启用画布拖拽
    });
    chart
      .treemap()
      .data({
        type: "fetch",
        value: "http://localhost:2000/echarts.json",
      })
      .layout({
        path: (d) => d.name.replace(/\./g, "/"),
        tile: "treemapBinary",
        paddingInner: 1,
      })
      .encode("value", "scale")
      .scale("color", { range: schemeTableau10 })
      .style(
        "labelText",
        (d) =>
          d.data.name
            .split(".")
            .pop()
            .split(/(?=[A-Z][a-z])/g)[0],
      )
      .style("labelFill", "#000")
      .style("labelPosition", "top-left")
      .style("fillOpacity", 0.5);
    chart.options({ slider: {} });

    // 渲染图表
    chart.render();

    // 设置定时更新
    timer = setInterval(updateChartData, 3000);
  } catch (error) {
    console.error("图表初始化失败:", error);
  }
};

// 数据处理函数
const processTreemapData = (data, percentageData) => {
  function transformNode(node, level = 0) {
    const result = {
      name: node.name,
      code: node.code,
      value: node.scale || 1, // 确保有value值
    };

    if (node.children && node.children.length > 0) {
      result.children = node.children.map((child) =>
        transformNode(child, level + 1),
      );
      // 计算父节点的value为子节点value的总和
      result.value = result.children.reduce(
        (sum, child) => sum + child.value,
        0,
      );
    } else if (node.code) {
      const percentage = getPercentage(node.code, percentageData);
      if (percentage !== null) {
        result.percentage = percentage;
      }
    }

    return result;
  }

  return data.map((item) => transformNode(item));
};

// 获取百分比数据
const getPercentage = (code, percentageData) => {
  if (!code || !percentageData[code]) return null;
  const value = percentageData[code].split("|")[1];
  return parseFloat(value);
};

// 根据百分比获取颜色
const getColor = (percentage) => {
  const colorMap = [
    { range: ">=4", color: "#e41813" },
    { range: ">=3", color: "#be1207" },
    { range: ">=2", color: "#960f0f" },
    { range: ">=1", color: "#6d1414" },
    { range: "<=-4", color: "#28d742" },
    { range: "<=-3", color: "#1da548" },
    { range: "<=-2", color: "#106f2f" },
    { range: "<=-1", color: "#0a5421" },
    { range: "default", color: "#424454" },
  ];

  for (const item of colorMap) {
    if (
      (item.range === ">=4" && percentage >= 4) ||
      (item.range === ">=3" && percentage >= 3) ||
      (item.range === ">=2" && percentage >= 2) ||
      (item.range === ">=1" && percentage >= 1) ||
      (item.range === "<=-4" && percentage <= -4) ||
      (item.range === "<=-3" && percentage <= -3) ||
      (item.range === "<=-2" && percentage <= -2) ||
      (item.range === "<=-1" && percentage <= -1) ||
      item.range === "default"
    ) {
      return item.color;
    }
  }
};

// 更新节点数据
const updateNodeData = (nodes, percentageData) => {
  return nodes.map((node) => {
    const newNode = { ...node };
    if (newNode.children) {
      newNode.children = updateNodeData(newNode.children, percentageData);
    } else if (newNode.code) {
      const percentage = getPercentage(newNode.code, percentageData);
      if (percentage !== null) {
        newNode.percentage = percentage;
      }
    }
    return newNode;
  });
};
</script>

<template>
  <div id="container" style="width: 90vw; height: 90vh"></div>
  <el-button style="background-color: #28d742">-4%</el-button>
  <el-button style="background-color: #1da548">-3%</el-button>
  <el-button style="background-color: #106f2f">-2%</el-button>
  <el-button style="background-color: #0a5421">-1%</el-button>
  <el-button style="background-color: #424454">0%</el-button>
  <el-button style="background-color: #6d1414">1%</el-button>
  <el-button style="background-color: #960f0f">2%</el-button>
  <el-button style="background-color: #be1207">3%</el-button>
  <el-button style="background-color: #e41813">4%</el-button>
</template>

<style lang="scss">
.tooltip-content {
  .tooltip-title {
    width: 180px;
    padding: 10px 0;
    color: white;
    text-align: center;
  }

  .tooltip-text {
    padding: 5px 10px;
  }
}
</style>
